﻿using Goooodbye.Core.Entities;
using Goooodbye.Core.Repositories;
using Goooodbye.Core.Services;
using NLog;
using System;
using System.IO;
using System.Reflection;
using System.Text;

namespace Goooodbye.Infrastructure.Services
{
    public class DictImportService : IImportService
    {
        private static readonly Logger logger = LogManager.GetLogger(Assembly.GetExecutingAssembly().GetName().Name);
        private const string CSV_TOP_ROW = "词条,转换为,备注";
        private readonly IDictRepository dictRepository;

        public DictImportService(IDictRepository dictRepository)
        {
            this.dictRepository = dictRepository;
        }

        public int Import(FileInfo file, bool append)
        {
            int ret = 0;
            using (StreamReader sr = new StreamReader(file.FullName, Encoding.UTF8))
            {
                var topRow = sr.ReadLine();
                if (topRow == CSV_TOP_ROW)
                {
                    if (!append)
                    {
                        dictRepository.DeleteAll();
                    }
                    while (!sr.EndOfStream)
                    {
                        var fields = sr.ReadLine().Split(',');
                        if (fields.Length >= 3)
                        {
                            var term = fields[0].Replace("'", "’").Replace("\"", "”").Replace(":", "：").Trim();
                            var mapping = fields[1].Replace("'", "’").Replace("\"", "”").Replace(":", "：").Trim();
                            var note = fields[2].Replace("'", "’").Replace("\"", "”").Replace(":", "：").Trim();

                            var entity = new Dict(term, mapping, note)
                            {
                                Id = Guid.NewGuid().ToString()
                            };
                            ret += dictRepository.Insert(entity);
                        }
                    }
                }
                else
                {
                    var msg = "字典文件格式不正确";
                    logger.Warn($"执行导入操作失败：{msg}");
                    throw new FormatException(msg);
                }
            }
            logger.Info($"Imported: {ret}");
            return ret;
        }
    }
}
